<template>
  <div class="user-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <el-button type="primary" @click="navigateToUser">
          <el-icon><ArrowLeft/></el-icon>
          返回
        </el-button>
        <h2 class="page-title">用户列表</h2>
        <div class="operation-buttons">
          <el-button type="primary" class="add-user-btn" @click="handleAddUserClick">
            <el-icon><Plus /></el-icon> 添加用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="user-search-card">
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名"
            @keyup.enter="handleSearch"
            @clear="handleInputChange"
            @input="handleInputChange"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input 
            v-model="searchForm.email" 
            placeholder="请输入邮箱"
            @keyup.enter="handleSearch"
            @clear="handleInputChange"
            @input="handleInputChange"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表表格 -->
    <el-card class="user-table-card" v-loading="loading">
      <el-table
        ref="userTable"
        :data="userTableData"
        row-key="id"
        border
        stripe
        class="user-table"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
        <el-table-column prop="isActive" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" link @click="handleEditUser(row.id)">编辑</el-button>
            <el-button size="small" link @click="handleDeleteUser(row.id)" class="text-danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Plus, ArrowLeft } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';

// Router
const router = useRouter();

// Store
const userStore = useUserStore();

// 状态管理
const userTableData = ref([]);
const selectedUserId = ref('');
const loading = ref(false);
const currentSearchForm = ref({}); // 当前搜索条件
let searchTimer = null; // 搜索防抖定时器

// 搜索表单
const searchForm = reactive({
  username: '',
  email: ''
});

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 生命周期钩子
onMounted(() => {
  fetchUserData();
});

// 获取用户数据
const fetchUserData = async () => {
  try {
    loading.value = true;
    
    const token = userStore.token;
    let params = new URLSearchParams({
      page: pagination.value.currentPage,
      size: pagination.value.pageSize
    });
    
    // 添加搜索参数
    if (currentSearchForm.value.username?.trim()) {
      params.append('userName', currentSearchForm.value.username.trim());
    }
    if (currentSearchForm.value.email?.trim()) {
      params.append('email', currentSearchForm.value.email.trim());
    }
    
    // 统一使用搜索API，当没有搜索条件时，会返回所有用户
    const apiUrl = '/api/users/search';
    const fullUrl = `${apiUrl}?${params.toString()}`;
    console.log('调用API:', fullUrl);
    
    const apiResponse = await fetch(fullUrl, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!apiResponse.ok) {
      throw new Error(`HTTP ${apiResponse.status}: ${apiResponse.statusText}`);
    }
    
    const apiResult = await apiResponse.json();
    console.log('API响应:', apiResult);
    
    // 处理数据映射：将后端的 UserName 映射为前端期望的 username
    const mappedItems = (apiResult.data.items || []).map(user => ({
      ...user,
      username: user.userName || user.UserName, // 兼容两种命名
      id: user.id
    }));
    
    // 更新表格数据
    userTableData.value = mappedItems;
    
    // 更新分页信息
    pagination.value = {
      currentPage: apiResult.data.pageIndex || pagination.value.currentPage,
      pageSize: apiResult.data.pageSize || pagination.value.pageSize,
      total: apiResult.data.totalCount || 0
    };
    
    console.log('用户数据:', userTableData.value);
    console.log('分页信息:', pagination.value);
    
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = async (showMessage = true) => {
  console.log('开始搜索，参数:', searchForm);
  
  // 更新当前搜索条件
  currentSearchForm.value = { 
    username: searchForm.username?.trim() || '',
    email: searchForm.email?.trim() || ''
  };
  
  // 重置到第一页
  pagination.value.currentPage = 1;
  
  console.log('当前搜索表单:', currentSearchForm.value);
  
  // 调用统一的数据获取函数
  await fetchUserData();
  
  // 只有在显示消息标志为true时才显示提示
  if (showMessage) {
    if (userTableData.value.length > 0) {
      ElMessage.success(`搜索完成，找到 ${pagination.value.total} 条记录`);
    } else {
      ElMessage.info('未找到匹配的用户');
    }
  }
};

// 处理输入变化（防抖搜索）
const handleInputChange = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  // 设置新的定时器，500ms后执行搜索（不显示提示消息）
  searchTimer = setTimeout(() => {
    handleSearch(false);
  }, 500);
};

// 重置搜索
const resetSearch = () => {
  // 清除防抖定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
    searchTimer = null;
  }
  
  searchForm.username = '';
  searchForm.email = '';
  currentSearchForm.value = {};
  pagination.value.currentPage = 1;
  fetchUserData();
  ElMessage.success('搜索条件已重置');
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  fetchUserData();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  fetchUserData();
};

// 处理行点击
const handleRowClick = (row) => {
  selectedUserId.value = row.id;
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  if (selection.length > 0) {
    selectedUserId.value = selection[0].id;
  } else {
    selectedUserId.value = '';
  }
};

// 处理编辑用户
const handleEditUser = (id) => {
  router.push(`/users/edit/${id}`);
};

// 处理删除用户
const handleDeleteUser = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await userStore.deleteuser(id);
    ElMessage.success('删除成功');
    fetchUserData(); // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 导航到添加用户页面
const handleAddUserClick = () => {
  router.push('/users/add');
};

// 返回用户管理页面
const navigateToUser = () => {
  router.push('/users');
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.user-search-card {
  margin-bottom: 20px;
}

.user-table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-danger {
  color: #f56c6c;
}
</style>
